<template>
  <div>
    <div
      style="padding:0;background-color:#ebeef5;min-height: calc(100vh - 60px)"
    >
      <div style="max-width: 1200px;margin: 0 auto">
        <!-- 订单列表 -->
        <div
          style="margin: 10px 0;background-color: #fff;padding: 20px;box-shadow: 0 1px 4px rgba(0,0,0,0.08)"
          v-loading="loading"
          element-loading-text="加载中..."
          element-loading-background="rgba(255, 255, 255, 0.8)"
        >

          <el-empty
            v-if="orders.length === 0 && !loading"
            description="暂无订单数据"
          />
          <div v-else>
            <div
              v-for="order in orders"
              :key="order.orderId"
              class="order-card"
            >
              <div class="order-header">
                <div style="display: flex;align-items: center;flex-wrap: wrap">
                  <span
                    style="font-size: 14px;color: #303133;margin-right: 20px"
                  >订单号：{{ order.orderId }}</span>
                  <span
                    style="font-size: 13px;color: #303133;">下单时间：{{ order.createTime }}</span>
                </div>
                <dict-tag
                  :options="dict.type.orders_status"
                  :value="order.status"
                />
              </div>

              <div style="display: flex;padding: 20px;flex-wrap:wrap;">
                <div
                  style="display: flex;margin-top: 15px;flex-wrap:wrap;line-height: 20px"
                >
                  <div style="flex:1">
                    <h4 style="margin: 0 0 10px;color: #5a5e66;">
                      {{ order.title }}</h4>
                    <div v-if="order.image">
                      <img :src="getOrderImage(order.image)" alt="订单图片" style="max-width: 200px; max-height: 150px; object-fit: cover; border-radius: 4px; margin: 10px 0;" />
                    </div>
                    <div class="homestay-location">
                      <i class="el-icon-location"></i>
                      <span>{{ order.location }}</span>
                    </div>
                    <div style="font-size: 14px;color: #5a5e66">
                      <span>入住时间：{{ order.checkInDate }}</span>
                      <span
                        style="margin-left: 10px">退房时间：{{ order.checkOutDate }}</span>
                    </div>
                  </div>
                </div>

                <div class="order-price">
                  <div class="price-item">
                    <span>单价：</span>
                    <span>￥{{order.price}}/晚</span>
                  </div>
                  <div class="price-item">
                    <span>天数：</span>
                    <span>{{order.days}}天</span>
                  </div>
                  <div class="price-item">
                    <span>总价：</span>
                    <span
                      style="color: #e47a4b;font-weight: bolder">￥{{order.totalAmount}}</span>
                  </div>

                  <div class="order-actions">
<!--                    <el-button-->
<!--                      size="mini"-->
<!--                      type="primary"-->
<!--                      @click="viewOrderDetail(order)"-->
<!--                    >查看详情</el-button>-->

                    <template v-if="order.status === '待支付'">
                      <el-button
                        size="mini"
                        type="success"
                        @click="handlePay(order)"
                      >立即支付</el-button>
                      <el-button
                        size="mini"
                        type="danger"
                        @click="handleCancel(order)"
                      >取消订单</el-button>
                    </template>

                    <template v-if="order.status === '已支付'">
                      <el-button
                        size="mini"
                        type="warning"
                        @click="handleRefund(order)"
                      >申请退款</el-button>
                    </template>

                    <template v-if="order.status === '已完成'">
                      <el-button
                        size="mini"
                        type="info"
                        @click="handleComment(order)"
                      >评价订单</el-button>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div
            class="pagination-container"
            style="text-align: center; margin-top: 20px;"
          >
            <el-pagination
              class="fixed-pagination"
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryParams.pageNum"
              :page-size="queryParams.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 支付对话框 -->
    <el-dialog
      title="订单支付"
      :visible.sync="paymentVisible"
      width="400px"
      center
    >
      <div class="payment-dialog">
        <div class="order-info">
          <p><strong>订单号：</strong>{{ currentOrder.orderId }}</p>
          <p><strong>订单金额：</strong>¥{{ currentOrder.totalAmount }}</p>
          <p><strong>账户余额：</strong>¥{{ userBalance }}</p>
        </div>

        <div class="payment-methods">
          <el-radio-group v-model="paymentMethod">
            <el-radio label="balance">余额支付</el-radio>
            <el-radio label="qrcode">扫码支付</el-radio>
          </el-radio-group>
        </div>

        <div
          v-if="paymentMethod === 'qrcode'"
          class="qrcode-container"
          v-loading="qrCodeLoading"
        >
          <img
            v-if="qrCodeUrl"
            :src="qrCodeUrl"
            alt="支付二维码"
            class="qrcode-img"
          >
          <p class="qrcode-tip">请使用微信或支付宝扫码支付</p>
          <el-button
            type="primary"
            size="small"
            @click="confirmPayment"
            :loading="paymentProcessing"
          >
            我已支付
          </el-button>
        </div>

        <div
          v-else
          class="balance-payment-info"
        >
          <template v-if="userBalance >= currentOrder.totalAmount">
            <p class="balance-sufficient">余额充足，可直接支付</p>
            <template>
              <!-- 支付按钮部分 -->
              <div class="payment-actions">
                <el-button
                  type="primary"
                  :loading="loading"
                  @click="handlePaymentConfirm">
                  确认支付
                </el-button>
              </div>
            </template>
          </template>
          <template v-else>
            <p class="balance-insufficient">余额不足，请选择其他支付方式</p>
            <el-button
              type="text"
              @click="handleRecharge"
            >去充值</el-button>
          </template>
        </div>

        <div class="payment-actions">
          <el-button @click="paymentVisible = false">取消</el-button>
<!--          <el-button-->
<!--            type="primary"-->
<!--            @click="handlePaymentStatus"-->
<!--            :disabled="paymentMethod === 'balance' && userBalance < currentOrder.totalAmount"-->
<!--          >-->
<!--            {{ paymentMethod === 'balance' ? '余额支付' : '确认已支付' }}-->
<!--          </el-button>-->
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrders, updateOrders } from "@/api/huacai/orders";
import { getUser } from "@/api/system/user";
import { updateUserAmount } from "@/api/huacai/homestay";

export default {
  name: "booking",
  dicts: ['orders_status'],

  data () {
    return {
      loading: false,
      orders: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'createTime',
        isAsc: 'desc'
      },
      paymentVisible: false,
      currentOrder: {},
      qrCodeUrl: '',
      qrCodeLoading: false,
      paymentTimer: null,
      paymentProcessing: false,
      userBalance: 0,
      paymentMethod: 'balance',
      currentPaymentId: null,
    }
  },

  created () {
    this.getList();
    this.getUserBalance();
  },

  methods: {
    getList () {
      this.loading = true;
      listOrders(this.queryParams).then(response => {
        this.orders = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    handleSizeChange (val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    handleCurrentChange (val) {
      this.queryParams.pageNum = val;
      this.getList();
      // 页面跳转后自动滚动到顶部
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    },

    viewOrderDetail (order) {
      this.$router.push({
        name: 'OrderDetail',
        params: { orderId: order.orderId }
      });
    },

    handlePay (order) {
      this.currentOrder = order;
      this.paymentVisible = true;
      this.generatePaymentQRCode();
    },

    /** 生成支付二维码 */
    generatePaymentQRCode () {
      this.qrCodeUrl = '';
      this.qrCodeLoading = true;
      this.currentPaymentId = null;

      // 生成唯一支付标识：时间戳+随机字符串
      const timestamp = Date.now();
      const randomStr = Math.random().toString(36).substring(2, 8);
      this.currentPaymentId = `PAY-${timestamp}-${randomStr}`;

      // 使用公共二维码API生成动态二维码
      this.qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(this.currentPaymentId)}&margin=10`;

      // 模拟API调用延迟
      setTimeout(() => {
        this.qrCodeLoading = false;
      }, 800);
    },

    async confirmPayment () {
      if (this.paymentProcessing) return;

      this.paymentProcessing = true;
      if (this.paymentTimer) {
        clearTimeout(this.paymentTimer);
        this.paymentTimer = null;
      }
      await updateOrders({
        orderId: this.currentOrder.orderId,
        status: '已支付'
      });
      this.paymentProcessing = false;
      this.handlePaymentSuccess();
    },

    handlePaymentSuccess () {
      this.$message.success('支付成功！');
      this.paymentVisible = false;
      this.getList();

      if (this.paymentTimer) {
        clearTimeout(this.paymentTimer);
        this.paymentTimer = null;
      }
    },

    getUserBalance () {
      getUser(this.$store.state.user.id).then(res => {
        this.userBalance = res.data.balance;
      });
    },

    handleCancel (order) {
      this.$confirm('确认取消该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrders({
          orderId: order.orderId,
          status: '已取消'
        }).then(() => {
          this.$message.success('订单已取消');
          this.getList();
        });
      }).catch(() => { });
    },

    handleRefund (order) {
      this.$confirm('确认申请退款吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        updateOrders({
          orderId: order.orderId,
          status: '已退款'
        }).then(() => {
          return updateUserAmount(order.totalAmount);
        }).then(() => {
          this.$message.success('退款申请已处理');
          this.getList();
          this.getUserBalance();
        }).catch(error => {
          console.error(error);
          this.$message.error('退款处理失败');
        }).finally(() => {
          this.loading = false;
        });
      }).catch(() => { });
    },

    handleComment (order) {
      this.$router.push({
        name: 'OrderDetail',
        params: {
          orderId: order.orderId,
          showComment: true
        }
      });
    },

    handleRecharge () {
      this.$router.push({
        path: '/index/recharge',
        query: {
          from: 'orderPayment',
          orderId: this.currentOrder.orderId
        }
      });
    },

    handlePaymentConfirm () {
      if (this.paymentMethod === 'balance') {
        if (this.userBalance >= this.currentOrder.totalAmount) {
          this.loading = true;
          updateUserAmount(-this.currentOrder.totalAmount).then(() => {
            return updateOrders({
              orderId: this.currentOrder.orderId,
              status: '已支付'
            });
          }).then(() => {
            this.$message.success('余额支付成功');
            this.paymentVisible = false;
            this.getList();
            this.getUserBalance();
          }).catch(error => {
            console.error(error);
            this.$message.error('支付失败');
          }).finally(() => {
            this.loading = false;
          });
        } else {
          this.$message.error('余额不足');
        }
      } else {
        this.confirmPayment();
      }
    },
    handlePaymentStatus () {
      if (this.currentOrder.status === '已支付') {
        this.$message.success('支付成功');
        this.paymentVisible = false;
        this.getList();
        this.getUserBalance();
      } else {
        this.$message.error('未支付');
      }
      console.log(this.currentOrder.status);
    },
    getOrderImage(image) {
      if (!image) return '';
      // 如果image是完整的URL，直接返回
      if (image.startsWith('http://') || image.startsWith('https://')) {
        return image;
      }
      // 否则，拼接服务器地址
      return process.env.VUE_APP_BASE_API + image;
    },
    beforeDestroy () {
      if (this.paymentTimer) {
        clearTimeout(this.paymentTimer);
      }
    }
  }
}
</script>

<style scoped>
.fixed-pagination {
  position: fixed;
  bottom: 20px;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  padding: 10px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
}

.order-card {
  border: 4px solid #ebeef5;
  border-radius: 5px;
  margin-bottom: 20px;
  transition: box-shadow 0.3s;
}

.order-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background-color: #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

.homestay-location {
  font-size: 13px;
  color: #909399;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.homestay-location i {
  margin-right: 5px;
}

.order-price {
  flex: 1;
  min-width: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-end;
  padding-right: 20px;
  margin-bottom: 15px;
  margin-top: 20px;
}

.price-item {
  margin-bottom: 8px;
  font-size: 14px;
  color: #5a5e66;
  white-space: nowrap;
}

.order-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.payment-dialog {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.order-info {
  width: 100%;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.order-info p {
  margin: 5px 0;
  font-size: 14px;
}

.payment-methods {
  width: 100%;
  margin: 15px 0;
}

.qrcode-container {
  text-align: center;
  margin: 15px 0;
}

.qrcode-img {
  width: 200px;
  height: 200px;
  margin-bottom: 10px;
}

.qrcode-tip {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
}

.balance-payment-info {
  width: 100%;
  margin: 15px 0;
  text-align: center;
}

.balance-sufficient {
  color: #67c23a;
}

.balance-insufficient {
  color: #f56c6c;
}

.payment-actions {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
